#include "UnityCG.cginc"
#include "UnityShaderVariables.cginc"

float4 BaseColor;

struct VS_IN {
    float4 vertex : POSITION;
    float3 normal : NORMAL;
};

struct FS_IN {
    float4 vertex : SV_POSITION;
    float3 vPos : TEXCOORD2;
    float3 vNom : TEXCOORD3;
};

#define VS_OUT FS_IN

struct FS_OUT {
    float depth : COLOR0;
    float3 vPos : COLOR1;
    float3 vNom : COLOR2;
    float3 flux : COLOR3;
};

VS_OUT vert (VS_IN i) {
    VS_OUT o = (VS_OUT)0;
    o.vertex = UnityObjectToClipPos(i.vertex);
    o.vPos = UnityObjectToViewPos(i.vertex.xyz);
    o.vNom = mul(UNITY_MATRIX_IT_MV, float4(i.normal, 0)).xyz;
    return o;
}

FS_OUT frag (FS_IN i) {
    FS_OUT o = (FS_OUT)0;
    o.depth = i.vertex.z / i.vertex.w;
    o.vPos = i.vPos;
    o.vNom = i.vNom;

    float tanHalfFov = unity_CameraProjection._m11;
    float2 clipImageHalfSize = 0;
    clipImageHalfSize.y = tanHalfFov;
    clipImageHalfSize.x = clipImageHalfSize.y * _ScreenParams.x / _ScreenParams.y;
    // float clipImagePixelLength = clipImageHalfSize.y * 2 / _ScreenParams.y;
    // float clipImagePixelArea = clipImagePixelLength * clipImagePixelLength;

    float3 clipImagePixelPos = 0;
    clipImagePixelPos.xy = clipImageHalfSize * i.vertex.xy / i.vertex.w;
    clipImagePixelPos.z = 1;
    float clipImagePixelDis = length(clipImagePixelPos);
	float dis = length(i.vPos);
    float pixelArea = dis / clipImagePixelDis;

	float Deg2Rad = UNITY_PI / 180;

	float3 vec = normalize(i.vPos);
	float atten = (vec.z > cos(20 * Deg2Rad)) ? 1 : 0;
    float3 I = float3(1, 1, 1) * atten;
    float Phi = saturate(dot(-vec, i.vNom)) * pixelArea / (dis * dis);
	o.flux = Phi * I * BaseColor * 1000;
	return o;
}